package zk;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

/**
 * ClassName ZkClient
 * Create by hx
 * Date 2021/7/15 9:39 下午
 */

public class ZkClient {

    //连接服务器端可多个，其中逗号左右不能有空格
    private String connectString = "localhost:2181";
    private int sessionTimeout = 2000;
    private ZooKeeper zkClient;

    /**
     * 初始化节点并监听
     * @throws IOException
     */
    @Before
    public void init() throws IOException {

        zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            public void process(WatchedEvent watchedEvent) {
                System.out.println("----------");
                List<String> children = null;
                try {
                    children = zkClient.getChildren("/", true);
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                for (String child : children){
                    System.out.println(child);
                }
                System.out.println("----------");
            }
        });
    }

    /**
     * 创建节点
     * @throws InterruptedException
     * @throws KeeperException
     */
    @Test
    public void create() throws InterruptedException, KeeperException {
        String node = zkClient.create("/mask","ss.avi".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    /**
     * 监听节点变化
     * @throws InterruptedException
     * @throws KeeperException
     */
    @Test
    public void getChildren() throws InterruptedException, KeeperException {
        List<String> children = zkClient.getChildren("/", true);
//        for (String child : children){
//            System.out.println(child);
//        }

        //延时
        Thread.sleep(Long.MAX_VALUE);
    }

    /**
     * 判断某个节点是否存在
     * @throws InterruptedException
     * @throws KeeperException
     */
    @Test
    public void exist() throws InterruptedException, KeeperException {
        Stat stat = zkClient.exists("/mask2", false);
        System.out.println(stat == null ? "not exist" : "exist");
    }

}
